/**
 * 拦截器
 */
import type { Interceptor } from '../index';

class InterceptorManager {
    readonly headers:Interceptor[]
    use:(fulfilled:Interceptor['fulfilled'], reject:Interceptor['reject']) => number
    eject:(id:number) => void
    forEach:(fn:(h:Interceptor) => void) => void
    constructor() {
      this.headers = [];
    }
}

// 设置拦截器 add interceptor
InterceptorManager.prototype.use = function use (fulfilled, reject) {
  (this as InterceptorManager).headers.push({
    fulfilled,
    reject
  })
  return (this as InterceptorManager).headers.length - 1
}

// 取消拦截器 remove interceptor
InterceptorManager.prototype.eject = function eject (id) {
  if ((this as InterceptorManager).headers[id]) {
    (this as InterceptorManager).headers[id] = null
  }
}

// 运行拦截器
InterceptorManager.prototype.forEach = function forEach (fn) {
  (this as InterceptorManager).headers.forEach(h => {
    if (h) {
      fn(h)
    }
  })
}

export default InterceptorManager;
